import 'dart:async';
import 'dart:convert';

import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:qianyi/state/token.dart';
import 'package:web_socket_channel/io.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
import 'package:get/get_state_manager/src/simple/get_controllers.dart';

import '../entity/message/UserRecord.dart';
import '../network/http_config.dart';
import '../network/http_entity.dart';
import '../network/http_manager.dart';
import '../view_model/message/message_chat_view_model.dart';
import '../view_model/message/message_view_model.dart';
/// WebSocket状态
enum SocketStatus {
  SocketStatusConnected, // 已连接
  SocketStatusFailed, // 失败
  SocketStatusClosed, // 连接关闭
}
class WebSocketController extends GetxController {
  WebSocketChannel? _channel;
  TokenController tokenController = Get.find();
  MessageViewModel? messageViewModel;
  MessageChatViewModel? messageChatViewModel;
  Timer? _reconnectTimer;
  SocketStatus? _socketStatus; // socket状态
  RxInt messageValue = 0.obs;
  RxMap<String,dynamic> listenData = RxMap<String,dynamic>();
  @override
  void onInit() async{
    super.onInit();
    // 确保在onInit中创建socket，以便在控制器被垃圾回收时关闭socket
    reconnect();

    initMessage();
  }

  initMessage() async {
    Map<String, dynamic> params = {};

    // String id = UserManager.userEntity!.userInfo!.id!;

    params["uid"] = await tokenController.getUid();;

    HttpEntity? result = await HttpManager.getInstance().request(url: "/platform/user/getUserRecord", params: params,method: Method.get) as HttpEntity;

    UserRecord listResult = UserRecord.fromJson(result.getOriData()["data"]);
    UserRecord temps = listResult; // 这里不需要强制类型转换
    if (temps != null) {

    }

    setListenData(result.getOriData()['data']);
  }
  @override
  void onClose() {
    super.onClose();
    // 确保在onClose中关闭socket，以便释放资源

  }

  void setListenData(Map<String,dynamic> oriData) {
    this.listenData.value["agreeCollectionCount"] = int.parse(oriData["agreeCollectionCount"]) ;
    this.listenData.value["addFollowCount"] = int.parse(oriData["addFollowCount"]) ;
    this.listenData.value["noreplyCount"] = int.parse(oriData["noreplyCount"]) ;
    this.listenData.value["uid"] = oriData["uid"];
    this.messageValue.value = int.parse(oriData["agreeCollectionCount"]);

  }

  Future<void> reconnect() async {
    String uid = await tokenController.getUid();

    // 确保旧的_channel被关闭
    if(_channel != null) {
      _channel?.sink?.close();

    }

    // 尝试重新连接WebSocket
    _channel = IOWebSocketChannel.connect("ws://www.loving666.sbs:8802/api/platform/ws/${uid}"  );

    // 监听连接状态，并在断开时尝试重新连接
    _channel!.stream.listen(
          (data) {
        // 处理接收到的数据
            messageViewModel!.onrefreshXt();
            messageChatViewModel!.onRefresh();
            listenData.value = jsonDecode(data);
            String jsonObj = data;
      },
      onError: (error) {
        // 处理错误并尝试重新连接

        Future.delayed(Duration(seconds: 10), reconnect);
      },
      onDone: () {
        // 连接完成，可能需要重新连接

          Future.delayed(Duration(seconds: 10), reconnect);


      },
      cancelOnError: true,
    );
  }

}
